/**
 * @Author 韦建韩
 * @Date 2022/5/5
 */
package com.example.devops.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.devops.Manage.HttpPortCache;
import com.example.devops.Manage.RecentlyPublishCache;
import com.example.devops.Manage.UserManager.UserInfoManage;
import com.example.devops.dao.MirrorCreateMapper;
import com.example.devops.dao.ProjectMapper;
import com.example.devops.dao.PublishHistoryMapper;
import com.example.devops.entity.common.Result;
import com.example.devops.entity.pojo.MirrorInformation;
import com.example.devops.entity.pojo.Project;
import com.example.devops.entity.pojo.PublishHistory;
import com.example.devops.entity.pojo.User;
import com.example.devops.exception.ValidationException;
import com.example.devops.service.IProjectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class ProjectPublishService implements IProjectService {
    Logger log = LoggerFactory.getLogger(ProjectPublishService.class);
    @Autowired
    ProjectMapper projectMapper;
    @Autowired
    PublishHistoryMapper publishHistoryMapper;
    @Autowired
    HttpPortCache httpPortCache;
    @Autowired
    MirrorCreateMapper mirrorCreateMapper;
    @Override
    public Result projectPublish(Long id) throws ParseException {
        MirrorInformation mirrorInformation = mirrorCreateMapper.selectById(id);
        String publishDate = mirrorInformation.getPublishDate();
        if(Objects.nonNull(publishDate)){
            String[] split = publishDate.split("-");
            long start = Long.parseLong(split[0]);
            long end = Long.parseLong(split[1]);
            Date start1 = new Date(start);
            Date end1 = new Date(end);
            Date now = new Date(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            String s1 = sdf.format(start1);
            String n1 = sdf.format(now);
            String e1 = sdf.format(end1);
            start1 = sdf.parse(s1);
           now = sdf.parse(n1);
            end1 = sdf.parse(e1);
            if(now.after(start1) && now.before(end1)){
                httpPortCache.init();
                String port = HttpPortCache.getPort();
                if (Objects.isNull(port)) {
                    throw new ValidationException("已经没有可用的端口号，请联系管理员扩展!");
                }
            }
            else{
                throw new ValidationException("现在不在发布窗口，无法发布");
            }
        }

        return Result.doCreate();
    }

    @Override
    public Result UpdateProject(Project project) {

        return null;
    }

    @Override
    public Result deleteProject(Project project) {
        return null;
    }

    @Override
    public Result findAllProjectByMember() {
        return null;
    }

    @Override
    public Result recentlyPublish() {
        User user = UserInfoManage.get();
        List<RecentlyPublishCache.Entity> entities = RecentlyPublishCache.get();
        return Result.doCreate(entities);
    }

    @Override
    public Result getPublishInstance(Long id) {
        QueryWrapper q = new QueryWrapper();
        q.eq("mirror_id", id);
        List list = projectMapper.selectList(q);
        return Result.doCreate(list);
    }

    @Override
    public Result insertSuccessProject(String branch, String mirrorId, String port, MirrorInformation mirrorInformation) {
        Project project = new Project();
        project.setBranch(branch);
        project.setMirrorId(Long.valueOf(mirrorId));
        project.setPort(port);
        project.setUrlAddr("http://124.223.52.229:"+port);
        project.setState("运行中");
        project.setName(mirrorInformation.getName());
        log.info("insert project:{}",project.toString());
        projectMapper.insert(project);
        savePublish(mirrorInformation.getName(), mirrorInformation.getUserId());
        return null;
    }

    @Override
    public Result findAllInstance() {
        List list = projectMapper.selectList(null);
        return Result.doCreate(list);
    }

    public void savePublish(String name,Long userId){
        PublishHistory publishHistory = new PublishHistory();
        publishHistory.setPublishDate(System.currentTimeMillis());
        publishHistory.setName(name);
        publishHistory.setState("发布成功");
        publishHistory.setPublishUserId(userId);
        publishHistoryMapper.insert(publishHistory);
    }
}
